package dragon.oauth.jwt;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
//注解说明：在yml中，如果imooc.security.oauth2.storeType的值为jwt，那么此配置生效，matchIfMissing = true表示如果yml没有该配置项，则下面的内容也生效
@ConditionalOnProperty(prefix = "imooc.security.oauth2",name = "storeType",havingValue = "jwt",matchIfMissing = true)
public class JWTConfigurer {

    public static final String JWT_SIGNING_KEY = "GOOD";

    /**
     * 负责生成token
     * @return
     */
    @Bean
    JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //配置验证秘钥,发令牌和验证token都是用这个，jwt的唯一安全控制
        converter.setSigningKey(JWT_SIGNING_KEY);
        return converter;
    }

    /**
     * 负责存储token，创建此store，需要提供JwtAccessTokenConverter
     * @return
     */
    @Bean
    JwtTokenStore jwtTokenStore(){
        System.out.println("生成jwtTokenStore");
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    //如果没有这个bean，则系统new一个JwtTokenEnhancer来代替
    @ConditionalOnMissingBean(name = "jwtTokenEnhancer")
    TokenEnhancer jwtTokenEnhancer(){
        return new JWTTokenEnhancer();
    }
}
